from user.dataCheck import DataCheck
import pdb, os, requests, json
import logging
from conf.sysConfig import config
# from software.views.view_software import tolist
from pprint import pprint
from django.http import JsonResponse

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
containerServerIP = config["containerServerIP"]
containerServerPort = config["containerServerPort"]
containerServerListUrl = config["containerServerListUrl"]
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def containerList(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])
    try:
        bo, total, size, current, pages, newRecords = tttt(requestParam['maxItem'], requestParam['page'] - 1)
    except:
        data = {
            "code": 1,
            "msg": "容器级服务调度不可用",
        }
        logger_request.info(data)
        return JsonResponse(data)
    if not bo:
        data = {
            "code": 1,
            "msg": "容器级服务调度不可用",
        }
        logger_request.info(data)
        return JsonResponse(data)
    data = {
        "code": 0,
        "total": total,
        "size": size,
        "current": current,
        "pages": pages,
        "newRecords": newRecords,
    }
    logger_request.info(data)
    return JsonResponse(data)


def tttt(pageSize, pageIndex):
    headers = {
        'centerkey': 'onlineproduct',
        'Content-Type': "application/json"
    }

    body = {
        "pageSize": pageSize,
        "pageIndex": pageIndex,
        "direction": "",
        "sortField": "",
        "filterKey": "",
    }
    token = requests.post(
        containerServerIP + ":" + containerServerPort + containerServerListUrl,
        data=json.dumps(body),
        headers=headers
    )
    data = json.loads(token.text)
    if not data['success']:
        return False
    new = data["data"]
    total = new['total']
    size = new['size']
    current = new['current']
    pages = new['pages']
    records = new['records']
    # pprint(len(records))
    newRecords = []

    for i in records:
        item = {
            'chName': i['chName'],
            'company': i['company'],
            'createTime': i['createTime'],
            'packageArch': i['packageArch'],
            'id': i['id'],
            'description': i['description'],
            'packageName': i['packageName'],
            'packageVer': i['packageVer'],
            'packagesize': i['packagesize']
        }
        newRecords.append(item)
        # pprint(newRecords)
    return True, total, size, current, pages, newRecords

# if __name__ == '__main__':
#     pprint(tttt(10, 0)[5])
